package com.example.adabank3.shiro;

import com.example.adabank3.entity.Users;
import com.example.adabank3.mapper.UsersMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;


/**
 * 验证和授权的逻辑的实现。
 * @author Administrator
 */
public class UserRealm extends AuthorizingRealm {

    @Resource
    UsersMapper userMapper;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("AuthorizationInfo->执行了授权");
        //SimpleAuthorizationInfo
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        Users currentUser = (Users) subject.getPrincipal();
        //授权
        info.addStringPermission(currentUser.getPerms());
        System.out.println("当前用户授权完毕");
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("AuthenticationInfo->执行了认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        System.out.println("realm:"+token);
        Users user = userMapper.selectByPrimaryName(token.getUsername());
        if(user == null){
            return null;
        }
        System.out.println("认证中");
        //密码认证
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
